﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MigraDoc.DocumentObjectModel;
using Payroll.BusinessLogic.CustomerManager;
using Payroll.BusinessLogic.Utils;
using Payroll.Common.Utils;
using PayrollHR.Web;

namespace PayrollHR.Administration.Modules
{
    public partial class FeesScheduleControl : BasePayrollAdministrationUserControl
    {
        private decimal m_grdTotalUSD = 0;
        private decimal m_grdTotalVND = 0;
        private decimal m_grdPayTotalUSD = 0;
        private decimal m_grdHaveToPayVND = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.FillFeesTypeDropDowns();
                this.FillCoursesDropDowns();
               // List<FeesSchedule> List = this.CustomerService.GetAllFeesScheduleByCustomerId(CustomerID);
                //for (int i = 0; i < List.Count; i++)
                //{
                //    List[i].FessName = ((Objects)this.CustomerService.GetObjectById(3).Where(p => p.ObjectId == List[i].FeesTypeID).ToList()[0]).ObjectName;
                //    List[i].CoursName = ((Objects)this.CustomerService.GetObjectById(2).Where(p => p.ObjectId == List[i].Courses).ToList()[0]).ObjectName;
                //    List[i].DateSubmitted = DateTime.MaxValue.ToShortTimeString();
                //}
              //  ViewState["FeesSchedule"] = List;
                //this.SumTotal(List);
               // gvFeesSchedule.DataSource = List;
                gvFeesSchedule.DataBind();
            }
            else {
                gvFeesSchedule.DataSource = (List<FeesSchedule>)ViewState["FeesSchedule"];
                gvFeesSchedule.DataBind();
            }
        }
        #region
        private void FillFeesTypeDropDowns()
        {
            //ddlFeesTypeID.Items.Clear();
            //var FeesTypeCollection = this.CustomerService.GetObjectById(3);
            //if (FeesTypeCollection.Count != 1)
            //{
            //    FeesTypeCollection.Insert(0, new Objects { ObjectId = 0, ObjectName = "-None-" });
            //}
            //foreach (Objects feestype in FeesTypeCollection)
            //{
            //    ListItem ddlFeesTypeItem2 = new ListItem(feestype.ObjectName, feestype.ObjectId.ToString());
            //    ddlFeesTypeID.Items.Add(ddlFeesTypeItem2);
            //}
        }
        private void FillCoursesDropDowns()
        {
            //dllCourses.Items.Clear();
            //var courseCollection = this.CustomerService.GetObjectById(2);
            //if (courseCollection.Count != 1)
            //{
            //    courseCollection.Insert(0, new Objects { ObjectId = 0, ObjectName = "-None-" });
            //}
            //foreach (Objects feestype in courseCollection)
            //{
            //    ListItem ddlcourseItem2 = new ListItem(feestype.ObjectName, feestype.ObjectId.ToString());
            //    dllCourses.Items.Add(ddlcourseItem2);
            //}
        }
        protected void BindGrid()
        {
            int customerId = CommonHelper.ToInteger(hfCustomerId.Value);
            //List<FeesSchedule> List = this.CustomerService.GetAllFeesScheduleByCustomerId(customerId);
            //ViewState["FeesSchedule"] = List;
            //this.SumTotal(List);
            //gvFeesSchedule.DataSource = List;
            gvFeesSchedule.DataBind();

        }
        public List<FeesSchedule> GetFeesSchedule()
        {
            List<FeesSchedule> List = new List<FeesSchedule>();
            if (ViewState["FeesSchedule"] != null)
            {
                List = (List<FeesSchedule>)ViewState["FeesSchedule"];
            }
            return List;
        }

        protected void processAjaxError(Exception exc)
        {
            ProcessException(exc, false);
            pnlError.Visible = true;
            lErrorTitle.Text = exc.Message;
        }
        #endregion
        #region btn
        protected void btnAddFeesSchedule_Click(object sender, EventArgs e)
        {
            int feetypeId = 0;
            int couseid = 0;
            try
            {
                if (ddlFeesTypeID.SelectedIndex > 0)
                {
                    feetypeId = CommonHelper.ToInteger(ddlFeesTypeID.SelectedItem.Value);
                }
                if (dllCourses.SelectedIndex > 0)
                {
                    couseid = CommonHelper.ToInteger(dllCourses.SelectedItem.Value);
                }
                List<FeesSchedule> List = GetFeesSchedule();
                FeesSchedule profile = new FeesSchedule
                {
                    FeesScheduleID = 0,
                    FeesTypeID = feetypeId,
                    FessName = ddlFeesTypeID.SelectedItem.Text,
                    Courses = couseid,
                    CoursName = dllCourses.SelectedItem.Text,
                    AmountUSD = txtAmountUSD.Value,
                    AmountVND = txtAmountVND.Value,                    
                    HaveToPayUSD = txtHaveToPayUSD.Value,
                    HaveToPayVND = txtHaveToPayVND.Value,
                    DateSubmitted = dpDate.SelectText,
                    UpdateByID = 1,
                    CreateByID = 1,
                    CreatedOn = Convert.ToDateTime(DateTime.Today),
                    UpdatedOn = Convert.ToDateTime(DateTime.Today)
                };
                List.Add(profile);
                this.SumTotal(List);
                ViewState["FeesSchedule"] = List;
                gvFeesSchedule.DataSource = List;
                gvFeesSchedule.DataBind();
                
            }
            catch (Exception exc)
            {
                 
            }
        }
        #endregion
        /// <summary>
        /// Gets or sets the customer ID.
        /// </summary>
        /// <value>
        /// The customer ID.
        /// </value>
        public int CustomerID
        {
            get
            {
                return CommonHelper.QueryStringInt("CustomerId");
            }
            set
            {
                hfCustomerId.Value = CommonHelper.ToString(this.CustomerID);
            }
        }

        protected void gvFeesSchedule_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int index = e.RowIndex;
                GridViewRow row = gvFeesSchedule.Rows[index];
                HiddenField hfFeesScheduleID = row.FindControl("hfFeesScheduleID") as HiddenField;
                List<FeesSchedule> listProfile = this.GetFeesSchedule();
                if (listProfile != null)
                {
                    listProfile.RemoveAt(index);
                    ViewState["FeesSchedule"] = listProfile;
                    if (CommonHelper.ToInteger(hfFeesScheduleID.Value) > 0)
                    {
                        List<int> List = new List<int>();
                        List.Add(CommonHelper.ToInteger(hfFeesScheduleID.Value));
                       // this.CustomerService.DeleteFeesSchedule(List);
                    }
                    this.SumTotal(listProfile);
                    gvFeesSchedule.DataSource = listProfile;
                    gvFeesSchedule.DataBind();                    
                }
            }
            catch (Exception exc)
            {
                processAjaxError(exc);
            }
        }

        protected void gvFeesSchedule_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                GridViewRow gvHeader = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

                TableCell headerCell0 = new TableCell()
                {
                    Text = "Loại phí",
                    CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    RowSpan = 2
                };
                TableCell headerCell1 = new TableCell()
                {
                    Text = "Khóa học",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    RowSpan = 2
                };

                TableCell headerCell2 = new TableCell()
                {
                    Text = "Số tiền",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    ColumnSpan = 2
                };

                TableCell headerCell3 = new TableCell()
                {
                    Text = "Đã đóng",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    ColumnSpan = 2
                };

                TableCell headerCell4 = new TableCell()
                {
                    Text = "Ngày nộp",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    RowSpan = 2
                };

                TableCell headerCell5 = new TableCell()
                {
                    Text = "Balance",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    ColumnSpan = 2
                };

                TableCell headerCell6 = new TableCell()
                {
                    Text = "Delete",
                    //CssClass = "HeaderStyle",
                    HorizontalAlign = HorizontalAlign.Center,
                    RowSpan = 2
                };

                e.Row.Cells.Remove(e.Row.Cells[0]);
                e.Row.Cells.Remove(e.Row.Cells[1]);
                e.Row.Cells.Remove(e.Row.Cells[4]);
                e.Row.Cells.Remove(e.Row.Cells[6]);


                gvHeader.Cells.Add(headerCell0);
                gvHeader.Cells.Add(headerCell1);
                gvHeader.Cells.Add(headerCell2);
                gvHeader.Cells.Add(headerCell3);
                gvHeader.Cells.Add(headerCell4);
                gvHeader.Cells.Add(headerCell5);
                gvHeader.Cells.Add(headerCell6);

                gvFeesSchedule.Controls[0].Controls.AddAt(0, gvHeader);
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = e.Row.FindControl("lbDelete") as LinkButton;
                if (btnDelete != null)
                    btnDelete.CommandArgument = e.Row.RowIndex.ToString();


                decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "AmountUSD"));
                decimal rowTotalVND = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "AmountVND"));
                decimal rowTotalPayUSD = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "HaveToPayUSD"));
                decimal roeTotallblHaveToPayVND = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "HaveToPayVND")); //lblTemplateHaveToPayVND
                #region format
                ((Label)e.Row.FindControl("lblTemplateUSD")).Text = rowTotal.ToString("C2");
                ((Label)e.Row.FindControl("lblTemplateVND")).Text = rowTotalVND.ToString("C2");
                ((Label)e.Row.FindControl("lblTemplateHaveToPayUSD")).Text = rowTotalPayUSD.ToString("C2");
                ((Label)e.Row.FindControl("lblTemplateHaveToPayVND")).Text = roeTotallblHaveToPayVND.ToString("C2");
                #endregion
                #region
                //m_grdTotalUSD += rowTotal;
                //m_grdTotalVND += rowTotalVND;
                //m_grdPayTotalUSD += rowTotalPayUSD;
                //m_grdHaveToPayVND += roeTotallblHaveToPayVND;
                #endregion

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                string[] total = ViewState["total"].ToString().Split('-');
                Label lblUSD = (Label)e.Row.FindControl("lblUSD");
                lblUSD.Text = decimal.Parse(total[0]).ToString("c");
                Label lblVND = (Label)e.Row.FindControl("lblVND");
                lblVND.Text = decimal.Parse(total[1]).ToString("c");
                Label lblPayUSD = (Label)e.Row.FindControl("lblPayUSD");
                lblPayUSD.Text = decimal.Parse(total[2]).ToString("c");
                Label lblPayVND = (Label)e.Row.FindControl("lblPayVND");
                lblPayVND.Text = decimal.Parse(total[3]).ToString("c");
            }
        }
        private void SumTotal(List<FeesSchedule> List)
        {
            decimal totalAmountUSD = 0;
            decimal totalAmountVNS = 0;
            decimal totalPayUSD = 0;
            decimal totalPayVND = 0;
            foreach (var feeSchedule in List)
            {
                totalAmountUSD += feeSchedule.AmountUSD;
                totalAmountVNS += feeSchedule.AmountVND;
                totalPayUSD += feeSchedule.HaveToPayUSD;
                totalPayVND += feeSchedule.HaveToPayVND;
            }
            ViewState["total"] = string.Format("{0}-{1}-{2}-{3}", totalAmountUSD, totalAmountVNS, totalPayUSD, totalPayVND);
        }
        
    }
}